<?php

namespace cms\modules\v1\models\im;

use cms\modules\v1\models\user\User;
use common\models\Functions;
use common\models\goods\GoodsTagRelation;
use common\models\group\Group;
use common\models\group\GroupApply;
use common\models\im\Im;
use common\models\Status;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class ImGroup extends Group
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id ASC';
//            $orderSql = $this->getOrder();

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getOrder()
    {
        $sort = Yii::$app->request->get('sort');

        $sort = json_decode($sort, true);

        if (empty($sort) || $sort['order'] == "normal") {
            return "id ASC";
        }
        $field = $sort['field'];

        return $field . " " . $sort['order'];

    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
        $name = Yii::$app->request->get('name','');
        $homeUserPhone = Yii::$app->request->get('phone','');
        $homeUserId = Yii::$app->request->get('id','');
        $startTime = Yii::$app->request->get('start', '');
        $endTime = Yii::$app->request->get('end', '');

        if ($name) {
            $andWhere[] = ['like','name',$name];
        }

        if ($homeUserPhone) {
            $andWhere[] = ['like','user_phone',$homeUserPhone];
        }

        if ($homeUserId) {
            $andWhere[] = ['like','user_tx_code',$homeUserId];
        }


        if ($startTime && $endTime) {
            $andWhere[] = ['between', 'create_time', $startTime, $endTime];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'owner' => function ($q) {
                $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
            },

        ])->asArray()->all();

        foreach ($list as &$v) {
            $singleOwnerInfo = ArrayHelper::getValue($v,'owner',[]);


            $v['pic'] = static::getImages($v['image']);

            $v['owner_id'] = $singleOwnerInfo['tx_code'] ?: '';
            $v['owner_phone'] = $singleOwnerInfo['login_name'] ?: '';
            $v['owner_user_face'] = static::getAvatar($singleOwnerInfo['user_face']);
            $v['owner_nick_name'] = $singleOwnerInfo['nick_name'] ?: '';
        }
        return $list;
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $where['id'] = $id;
            $info = static::getObjectByWhere($where)->with([
//                'tag' => function ($q) {
//                    $q -> select(['tag_id','goods_id']);
//                },
            ])->asArray()->one();
            if (empty($info)) {
                throw new Exception('未知信息');
            }

            $info['yx_num'] = floatval($info['yx_num']);
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $id = Yii::$app->request->post('id',0);
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            if (!empty($id)) {
                //更新操作
                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateData($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }

            } else {
                //添加操作
                $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 后台解散群
     * @param int $id
     * @return array
     */
    public function cancelGroup($id = 0) {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $groupId = $id ? $id : Yii::$app->request->post('id',0);

            if (!$groupId) {
                throw new Exception('未知群信息');
            }

            $groupInfo = static::getOneByWhere(['id' => $groupId]);
            if (!$groupInfo) {
                throw new Exception('未知群信息');
            }

            // 群成员信息  群申请信息全都删除 与 群信息
            $resGroupUserDel = ImGroupUser::deleteAll(['group_id' => $groupInfo['id']]);
            if ($resGroupUserDel === false) {
                throw new Exception('群解散失败！');
            }

            $resGroupApplyDel = GroupApply::deleteAll(['group_id' => $groupInfo['id']]);
            if ($resGroupApplyDel === false) {
                throw new Exception('群解散失败！');
            }

            $resGroupDel = static::deleteAll(['id' => $groupId]);
            if ($resGroupDel === false) {
                throw new Exception('群解散失败！');
            }


            // IM解散群
            $resImDel = (new Im())->delGroup($groupInfo['tx_code']);
            if (!$resImDel) {
                throw new Exception('群解散失败！');
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '解散成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 启用禁用 等切换装填
     * @param array $statusMap
     * @param string $filed
     * @return array
     */
    public function switchStatusGroup($statusMap = [], $filed = 'status') {
        try {
            $post = Yii::$app->request->post();

            $id = (int) $post['id'];
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $statusMap = $statusMap ? $statusMap : Status::commonStatusMap();
            $filed = $filed ? $filed : 'status';

            $afterStatus = (int) $post['status'];
            $afterStatusName = $statusMap[$afterStatus];

            $data[$filed] = $afterStatus;
            $data['update_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data, ['id' => $id]);
            if ($res === false) {
                throw new Exception($afterStatusName.'失败，请联系开发小哥哥');
            }

            $groupInfo = static::getOneByWhere(['id' => $id]);

            $updateImGroupDefineData['group_id'] = (string) $afterStatus;
            if ($updateImGroupDefineData) {
                // 更新IM群信息
                (new Im())->updateImGroup($groupInfo['tx_code'], [], $updateImGroupDefineData);
            }

            return Functions::formatRestAPI(0, $afterStatusName.'成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getMapForSelect() {
        $list = static::getByWhere();
        $result = [];
        foreach ($list as $v) {
            $result[] = [
                "id" => $v['id'],
                'name' => $v['name']
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }


}
